package jp.co.realsys.common.validator;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class DateStringFieldValidator extends FieldValidatorSupport {

	@Override
	public void validate(Object value) throws ValidationException {
		if (value == null) {
			return;
		}
		
		String str = null;
		if (!(value instanceof String)) {
			try {
				BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(value);
				Object fieldVal = wrapper.getPropertyValue(getFieldName());
				if ((fieldVal instanceof String) && fieldVal != null) {
					str = (String) fieldVal;
				} else {
					return;
				}
			} catch (Exception ex) {
				return;
			}
		} else {
			str = (String) value;
		}

		str = str.trim();
		if (str.length() == 0) {
			return;
		}

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			sdf.setLenient(false);
			sdf.parse(str);
		} catch (ParseException e) {
			addFieldError(getFieldName(), str);
		}
	}
	
}